package fun.qu_an.minecraft.mini_games_helper.network;

import fun.qu_an.minecraft.mini_games_helper.client.network.MGHClientNetworkHandler;
import fun.qu_an.minecraft.mini_games_helper.config.MiniGamesHelperConfig;
import lombok.Getter;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.networking.v1.*;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.network.ServerConfigurationNetworkHandler;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;

public record MGHConfigS2CPacket(MiniGamesHelperConfig config) implements FabricPacket {
	public static final PacketType<MGHConfigS2CPacket> TYPE = PacketType.create(ForceOptions.FORCE_OPTIONS, buf -> new MGHConfigS2CPacket(MiniGamesHelperConfig.get().deserialize(buf)));

	public static MGHConfigS2CPacket receiveFromServer(PacketByteBuf buf) {
		return TYPE.read(buf);
	}


	@Override
	public void write(PacketByteBuf buf) {
		this.config.serialize(buf);
	}

	@Environment(EnvType.CLIENT)
	public void onReceive() {
		MGHClientNetworkHandler.handle(this);
		System.out.println("applied!!!!");
	}

	@Override
	public PacketType<?> getType() {
		return TYPE;
	}

	public static void sendToClient(PacketSender sender, MiniGamesHelperConfig payload) {
		sender.sendPacket(new MGHConfigS2CPacket(payload));
		System.out.println("send force options to client!");
	}

	public static void sendToClient(ServerPlayNetworkHandler handler, MiniGamesHelperConfig payload) {
		sendToClient(ServerPlayNetworking.getSender(handler), payload);
	}

	public static void sendToClient(ServerPlayerEntity player, MiniGamesHelperConfig payload) {
		sendToClient(ServerPlayNetworking.getSender(player), payload);
	}

	public static void sendToClient(ServerConfigurationNetworkHandler handler, MiniGamesHelperConfig payload) {
		ServerConfigurationNetworking.send(handler, new MGHConfigS2CPacket(payload));
		System.out.println("send force options to client!");
	}
}
